<?php
/**
 * 通过键名获取数组中的键值
 *
 * @param   array   $array
 * @param   string  $key
 * @param   mix     $default
 * @param   boolean $int
 * @return  string  
 **/
function v($array,$key,$default = '',$int = false) {
    if(!$array) return '';

    if($key == 'status') {
        $value = isset($array[$key]) ? $array[$key] : $default;
    }else {
        $value = isset($array[$key]) && $array[$key] ? trim($array[$key]) : $default;
    }

    ($int === true) && ($value = intval($value));

    return $value;
}
/**
 * 验证数据并抛出异常
 *
 * @param    void
 * @return    void
 **/
function verify($value,$function,$message = '') {
    if(!class_exists('Verify')) {
        vendor('Util.Verify');
    }
    $result = Verify::$function($value);
    if($result === false && $message) {
        throw new \Exception($message);
    }
    return $result;
}
/**
 * 格式化时间戳
 *
 * @param   string  $timestamp
 * @return  string
 **/
function dateFormat($timestamp,$style = 1) {
    if($style === 1) {
        return date('Y-m-d H:i',$timestamp);
    }elseif($style === 2) {
        return date('Y-m-d H:i',$timestamp);
    }else {
        return date('Y-m-d H:i:s',$timestamp);
    }
}
/**
 * 上传图片
 *
 * @param   string  $name
 * @return  array
 **/
function uploadImage($name,$type = 'default',$index = 0) {
    if(!$_FILES || !isset($_FILES[$name]['tmp_name'])) {
        return false;
    }
    $error = $_FILES[$name]['error'];
    if($index) {
        $error = $error[$index];
        $tmp_name = $_FILES[$name]['tmp_name'][$index];
    }else {
        $tmp_name = $_FILES[$name]['tmp_name'];
    }
    if($error) {
        $error_map = array(
            1   =>  '文件大小超出了服务器的空间大小',
            2   =>  '要上传的文件大小超出浏览器限制',
            3   =>  '文件仅部分被上传',
            4   =>  '没有找到要上传的文件',
            5   =>  '服务器临时文件夹丢失',
            6   =>  '文件写入到临时文件夹出错',
        );
        throw new \Exception($error_map[$error]);
    }

    if(!class_exists('UploadImage')) {
        vendor('Util.UploadImage');
    }
    static $UploadImage = null;
    if($UploadImage === null) {
        $UploadImage = new UploadImage();
        $UploadImage->setTemppath(C('IMAGE_TMEP_PATH'));
    }
    $UploadImage->setType($type);
    try{
        return $UploadImage->save($tmp_name);
    }catch(\Exception $e) {
        return false;
    }
}

/**
 * 下载远程图片
 *
 * @param   string  $name
 * @return  array
 **/
function fetchImage($url,$type = 'default') {
    if(!class_exists('UploadImage')) {
        vendor('Util.UploadImage');
    }
    static $UploadImage = null;
    if($UploadImage === null) {
        $UploadImage = new UploadImage();
        $UploadImage->setTemppath(C('IMAGE_TMEP_PATH'));
    }
    $UploadImage->setType($type);

    try{
        return $UploadImage->fetch($url);
    }catch(\Exception $e) {
        return false;
    }
}
/**
 * 格式化图片地址
 *
 * @param   string  $path
 * @param   int     $width
 * @param   int     $height
 * @return  $string
 **/
function imageUrl($path,$width = 0,$height = 0) {
    if(!$path) return '';
    
    $style = "";
    if($width) $style = "{$width}w";
    if($height) $style = $style ? "{$style}_{$height}h" : "{$height}h"; 
    if($style && C('IMAGE_SAVE_ALIYUN')) {
        return C('IMAGE_DOMAIN') . $path . "@{$style}_1e_1c";
    }else {
        return C('IMAGE_DOMAIN') . $path;
    }
}
/**
 * 获取模板信息
 *
 * @param   int     $cid
 * @param   string  $field
 * @return  array || string 
 */
function getTemplate($tid,$field = '') {
    if(!verify($tid,'isID')) {
        return '';
    }
    static $Template = null;
    static $templateList = array();
    if(isset($templateList[$tid])) {
        $templateInfo = $templateList[$tid];
    }else{
        if($Template === null) $Template = M('template');
        $templateList[$tid] = $templateInfo = $Template->find($tid);
    }
    !$templateInfo && $templateInfo = array();

    return $field ? (isset($templateInfo[$field]) ? $templateInfo[$field] : '') : $templateInfo;
}
/**
 * 获取网站信息
 *
 * @param   int     $cid
 * @param   string  $field
 * @return  array || string 
 */
function getSite($sid,$field = '') {
    if(!verify($sid,'isID')) {
        return '';
    }
    static $Site = null;
    static $siteList = array();
    if(isset($siteList[$sid])) {
        $siteInfo = $siteList[$sid];
    }else{
        if($Site === null) $Site = M('Site');
        $siteList[$sid] = $siteInfo = $Site->find($sid);
    }
    !$siteInfo && $siteInfo = array();

    return $field ? (isset($siteInfo[$field]) ? $siteInfo[$field] : '') : $siteInfo;
}
/**
 * 获取分类信息
 *
 * @param   int     $cid
 * @param   string  $field
 * @return  array || string 
 */
function getCategory($cid,$field = '') {
    if(!verify($cid,'isID')) {
        return '';
    }
    static $Category = null;
    static $categoryList = array();
    if(isset($categoryList[$cid])) {
        $categoryInfo = $categoryList[$cid];
    }else{
        if($Category === null) $Category = M('Category');
        $categoryList[$cid] = $categoryInfo = $Category->find($cid);
    }
    !$categoryInfo && $categoryInfo = array();

    return $field ? (isset($categoryInfo[$field]) ? $categoryInfo[$field] : '') : $categoryInfo;
}
/**
 * 获取菜单信息
 *
 * @param   int     $sid
 * @param   string  $field
 * @return  array || string 
 */
function getMenu($id,$field = '') {
    if(!verify($id,'isID')) {
        return '顶级菜单';
    }
    static $Menu = null;
    static $menuList = array();
    if(isset($menuList[$id])) {
        $menuInfo = $menuList[$id];
    }else{
        if($Menu === null) $Menu = M('Menu');
        $menuList[$id] = $menuInfo = $Menu->find($id);
    }
    !$menuInfo && $menuInfo = array();

    return $field ? (isset($menuInfo[$field]) ? $menuInfo[$field] : '') : $menuInfo;
}
/**
 * 获取标签信息
 *
 * @param   int     $id
 * @param   string  $field
 * @return  array || string 
 */
function getTag($id,$field = '') {
    if(!verify($id,'isID')) {
        return '无标签';
    }
    static $Tags = null;
    static $tagList = array();
    if(isset($tagList[$id])) {
        $tagInfo = $tagList[$id];
    }else{
        if($Tags === null) $Tags = M('Tags');
        $tagList[$id] = $tagInfo = $Tags->find($id);
    }
    !$tagInfo && $tagInfo = array();

    return $field ? (isset($tagInfo[$field]) ? $tagInfo[$field] : '') : $tagInfo;
}
/**
 * 获取单页信息
 *
 * @param   int     $id
 * @param   string  $field
 * @return  array || string 
 */
function getPage($id,$field = '') {
    if(!verify($id,'isID')) {
        return '无标签';
    }
    static $Page = null;
    static $pageList = array();
    if(isset($pageList[$id])) {
        $pageInfo = $pageList[$id];
    }else{
        if($Page === null) $Page = M('Page');
        $pageList[$id] = $pageInfo = $Page->find($id);
    }
    !$pageInfo && $pageInfo = array();

    return $field ? (isset($pageInfo[$field]) ? $pageInfo[$field] : '') : $pageInfo;
}
/**
 * 获取解析器
 *
 * @param   int    $parseid
 * @param   string $field
 * @return  array || string 
 **/
function getParse($parseid,$field = '') {
    if(!verify($parseid,'isID')) {
        return '';
    }
    static $Parse = null;
    static $ParseList = array();
    if(isset($ParseList[$parseid])) {
        $parseInfo = $ParseList[$parseid];
    }else{
        if($Parse === null) $Parse = M('Parse');
        $ParseList[$parseid] = $parseInfo = $Parse->find($parseid);
    }
    !$parseInfo && $parseInfo = array();

    return $field ? (isset($parseInfo[$field]) ? $parseInfo[$field] : '') : $parseInfo;
}
/**
 * 中文分词
 *
 * @param   string  $content
 * @param   string  $field
 * @return  string
 **/
function segment($content,$field = '') {
    // 去除html标签
    $content = htmlspecialchars_decode($content);
    $content = strip_tags($content);
    $content = preg_replace("/[\s\n\t]+/",'',$content);
    $content = str_replace("'","\'",$content);

    if(!$content) return array();
    // 命令路径
    $bin = C('SCWS.BIN');
    // 词库
    $dict = implode(':',C('SCWS.DICT'));
    // 忽略的词性
    $ignore = C('SCWS.IGNORE');
    // 显示最高的单词数
    $topnum = C('SCWS.TOPNUM');
    // 命令，依赖scws
    $awk = "|awk '/^[0-9]/{gsub(/\(/,\":\",$4);gsub(/\)/,\"\",$4);print $2\":\"$3\":\"$4}'";
    $command = "{$bin} -i '{$content}' -c utf8 -d '{$dict}' -A -I -N -U -t {$topnum} -a '~{$ignore}' -M 4 {$awk}";
    // 执行并返回
    exec("{$command}",$output);

    if(!$output) return array();

    $list = array();
    foreach($output as $line) {
        $line = trim($line);
        $info = explode(':',$line);
        $info = array(
            'word'  =>  $info[0],
            'attr'  =>  $info[1],
            'weight'=>  $info[2],
            'num'   =>  $info[3],
        );
        if($field && isset($info[$field])) {
            $list[] = $info[$field];
        }else {
            $list[] = $info;
        }
    }
    return $list;
}
/**
 * （文章显示时）内容格式化
 *
 * @param   string  $content
 * @return  string
 **/
function contentFormat($content) {
    if(!$content) return '';

    $replace = array(
        '<img class="i" src="'  =>  '<img class="i" src="' . C('IMAGE_DOMAIN'),
        '<img class="i" data-src="'  =>  '<img class="i" src="' . C('IMAGE_DOMAIN'),
    );
    $content = str_replace(array_keys($replace),array_values($replace),$content);
    return $content;
}
/**
 * html清除方法
 *
 * @param   string  $content
 * @return  string
 **/
function clearHtml($content) {
    static $HtmlClear = null;
    if($HtmlClear === null) {
        $result = vendor('Util.HtmlClear');
        $HtmlClear = new \HtmlClear();
    }
    $content = $HtmlClear->html($content);
    return $content;
}
/**
 * 发送post请求
 *
 * @param     string    $api
 * @param     array     $post
 * @return    array
 **/
function post($api,$post) {
    static $Snoopy = null;
    if($Snoopy === null) {
        $Snoopy = new \Snoopy();
    }

    $result = $Snoopy->submit($api,$post);
    $content = $Snoopy->results;

    $code = explode(" ",$Snoopy->response_code)[1];
    if($code !== '200') {
        \Org\Util\Loger::error(array(
            'code'      =>  $code,
            'api'       =>  $api,
            'message'   =>  isset($httpCode[$code]) ? $httpCode[$code] : '服务器错误 httpcode:' . $code,
        ));
        return false;
    }
    $data = json_decode($content,true);
    if(!$data) {
        \Org\Util\Loger::error(array(
            'code'      =>  $code,
            'message'   =>  $content,
            'api'       =>  $api,
        ));
        return false;
    }

    return $data;
}
/**
 * 通过文章ID获取文章
 *
 * 主要用户模板文件中设置的文章列表数据
 *
 * @param     void
 * @return    void
 **/
function get_article_by_ids($ids,$limit = 10,$order='publishtime desc') {
    if(!$ids) return array();

    $where = array(
        'id'        =>  array('in',$ids),
        'status'    =>  1,
        'publishtime'   =>  array('lt',NOW_TIME),
    );
    
    $field = 'id,title,content,cid,author,hotnum,cover,tags,publishtime';

    $data = M('Article')->where($where)->limit('0,'.$limit)->field($field)->order($order)->select();

    return $data ? $data : array();
}

function get_tags_by_ids($ids,$limit=10) {
    if(!$ids) return array();

    $where = array(
        'id'        =>  array('in',$ids),
        'status'    =>  1,
    );
    
    $data = M('Tags')->where($where)->field('id,title,nickname,num')->select();

    return $data ? $data : array();
}

function get_article_desc($content,$length) {
    $content = mb_substr(strip_tags($content),0,$length,'utf-8');
    $content = str_replace("\n",'',$content);
    return $content;
}

function cache($sid,$type,$keys = '') {
    if(!$sid) return null;

    if(!in_array($type,array('site','category','menu','category_tags','template','link','advertise'))) return null;

    $keys = $type . '.' . $keys;

    static $siteCacheList = array();
    if(!isset($siteCacheList[$sid])) {
        $info = D('Site','Mongo')->get($sid);
        $siteCacheList[$sid] = $info;
    }else {
        $info = $siteCacheList[$sid];
    }
    if(!$info) return null;

    $keyArray = explode('.',$keys);
    foreach($keyArray as $key) {
        $info = isset($info[$key]) ? $info[$key] : null;
        if(!$info) break;
    }

    return $info;
}

function template_cache($sid,$keys) {
    return cache($sid,'template',$keys);
}

function subTitle($title,$length = 15) {
    $title = mb_substr(strip_tags($title),0,$length,'utf-8');
    $title = str_replace("\n",'',$title) . '...';
    return $title;
}

function arrayToString($array,$num = 0,$sep = ',') {
    if(!$array) return '';
    if($num) {
        $list = array();
        $i = 0;
        foreach($array as $value) {
            $list[] = $value;
            if(++$i >= $num) break;
        }
        $array = $list;
    }

    return implode($sep,$array);
}
?>
